<template>
  <a-card :bordered="false">
    <a-row :gutter="10">
      <a-col :xxl="4" :xl="6" :md="6" :sm="24">
        <a-alert
          :message="selectedTips"
          type="success"
          show-icon
          :banner="true"
          class="selectedTips"
        />
        <a-tree
          :tree-data="treeData"
          show-icon
          :default-expanded-keys="['index']"
          v-if="treeLoaded"
          @select="onSelect"
        ></a-tree>
      </a-col>

      <!-- :default-selected-keys="['root']" -->
      <a-col :xxl="20" :xl="18" :md="18" :sm="24">
        <div class="table-operator">
          <a-button-group>
            <a-button type="primary" icon="plus" @click="handleAdd">添加</a-button>
            <a-button type="primary" icon="plus" @click="handleEdit" :disabled="editBtnDisable">编辑</a-button>
            <a-button type="danger" icon="plus" @click="handleDel" :disabled="deleteBtnDisable">删除</a-button>
          </a-button-group>
        </div>
        <s-table
          ref="table"
          size="default"
          rowKey="key"
          :columns="columns"
          :data="loadData"
          :rowSelection="options.rowSelection"
          showPagination="auto"
        >
          <span slot="show" slot-scope="text, record, index">
            <!-- {{ text | statusTextFilter }} -->
            <a-tag
              v-if="text === 'show'"
              color="green"
              :status="text | statusFilter"
              :text="text | statusTextFilter"
            >{{ text | statusTextFilter }}</a-tag>
            <a-tag
              v-if="text === 'un_show'"
              color="cyan"
              :status="text | statusFilter"
              :text="text | statusTextFilter"
            >{{ text | statusTextFilter }}</a-tag>
          </span>
          <span slot="type" slot-scope="text, record, index">
            <a-tag
              v-if="text === 'menu'"
              color="green"
              :status="text | typeFilter"
              :text="text | typeTextFilter"
            >{{ text | typeTextFilter }}</a-tag>
            <a-tag
              v-if="text === 'action'"
              color="#2db7f5"
              :status="text | typeFilter"
              :text="text | typeTextFilter"
            >{{ text | typeTextFilter }}</a-tag>
          </span>
        </s-table>
      </a-col>
    </a-row>
    <menu-edit
      ref="menuEditModal"
      :visible.sync="visible"
      :loading="menuEditLoading"
      :model="menuEditModel"
    />
  </a-card>
</template>


<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import StepByStepModal from '../../list/modules/StepByStepModal'
import { getRoleList, getServiceList } from '@/api/manage'
import enums from '@/common/enums'
import { getMenuTree, getMenuListByPid } from '@/api/manage/admin'
import { isNull } from '@/utils/util'
import MenuEdit from './MenuEdit'
import { routerComponents } from '@/router/router'

const columns = [
  {
    dataIndex: 'id',
    key: 'id',
    title: 'id',
  },
  {
    dataIndex: 'pid',
    key: 'pid',
    title: 'pid',
    className: 'hidden',
  },
  {
    dataIndex: 'key',
    key: 'key',
    title: '唯一键',
  },
  {
    dataIndex: 'name',
    key: 'name',
    title: '名称',
    // slots: { title: 'customTitle' },
    // scopedSlots: { customRender: 'name' },
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '路径',
    dataIndex: 'path',
    key: 'path',
    className: 'hidden',
  },
  {
    title: '组件',
    key: 'component',
    dataIndex: 'component',
    scopedSlots: { customRender: 'component' },
  },
  {
    title: '图标',
    key: 'icon',
    scopedSlots: { customRender: 'action' },
  },
  {
    title: '排序',
    key: 'sort',
  },
  {
    title: '状态',
    key: 'show',
    dataIndex: 'show',
    scopedSlots: { customRender: 'show' },
    // scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'menu',
  components: {
    STable,
    Ellipsis,
    StepByStepModal,
    MenuEdit,
  },
  data() {
    return {
      menuEditModel: null,
      visible: false,
      menuEditLoading: false,
      // enums: enums,
      treeData: [],
      // 高级搜索 展开/关闭
      advanced: false,
      selectedTips: '当前选择项：',
      selectedTipsDefault: '当前选择项：',
      editBtnDisable: true,
      deleteBtnDisable: true,
      // 查询参数
      queryParam: {},
      treeLoaded: false,
      selectedNode: {
        pid: 0,
      },
      // 表头
      columns: columns,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return getMenuListByPid(Object.assign(parameter, this.queryParam)).then((res) => {
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      // custom table alert & rowSelection
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
        },
      },
    }
  },
  filters: {
    statusFilter(val) {
      return enums.show_status[val].value
    },
    statusTextFilter(val) {
      return enums.show_status[val].name
    },
    typeFilter(val) {
      return enums.permission_type[val].value
    },
    typeTextFilter(val) {
      return enums.permission_type[val].name
    },
  },
  created() {
    this.advanced = false
    this.tree()
    // this.queryParam = {
    //   pid: this.selectedNode.id || 0,
    // }
    this.queryParam.pid = this.selectedNode.id || 0
    // this.routerComponentsData = this.toarray(routerComponents)
  },
  watch: {
    selectedRows: {
      handler: function (val, oldval) {
        if (val) {
          if (val.length == 1) {
            this.editBtnDisable = !this.editBtnDisable
            this.deleteBtnDisable = !this.deleteBtnDisable
            this.menuEditModel = {
              type: 'edit',
              id: val[0].id,
              pid: isNull(this.selectedNode) ? 0 : this.selectedNode.id,
              component: isNull(this.selectedNode) ? '' : this.selectedNode.component,
            }
            return
          } else if (val.length > 1) {
            this.editBtnDisable = true
            this.deleteBtnDisable = false
            return
          }
        }
        this.editBtnDisable = true
        this.deleteBtnDisable = true
      },
    },
    deep: true,
    immediate: true,
  },
  methods: {
    tree() {
      var d = getMenuTree().then((data) => {
        this.treeLoaded = true
        this.treeData = data.data
        if (this.treeData && this.treeData.length > 0) {
          this.selectedNode = this.treeData[0]
          var rootTitle = this.treeData[0].title
          this.selectedTips = `${this.selectedTipsDefault}${rootTitle}`
        }
        return
        // return (this.treeData = data.data)
      })
    },
    handleAdd() {
      this.menuEditModel = {
        type: 'add',
        id: isNull(this.selectedNode) ? 0 : this.selectedNode.id,
        pid: isNull(this.selectedNode) ? 0 : this.selectedNode.id,
        component: isNull(this.selectedNode) ? '' : this.selectedNode.component,
      }
      // alert(JSON.stringify(this.selectedNode))
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.menuEditModel = {
        type: 'edit',
        id: isNull(this.selectedRows) ? 0 : this.selectedRows[0].id,
        pid: isNull(this.selectedNode) ? 0 : this.selectedNode.id,
        component: isNull(this.selectedNode) ? '' : this.selectedNode.component,
      }
    },
    handleCancel() {
      this.visible = false
      // const form = this.$refs.menuEditModal.form
      // form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    handleDel(){
      
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam.pid = this.selectedNode.id || 0
    },
    onSelect(selectedKeys, info) {
      var selected = this.findByTree(selectedKeys, this.treeData)
      // console.log(88, JSON.stringify(selected))
      if (!isNull(selected)) {
        this.selectedNode = selected[0]
        // console.log(888, this.selectedNode.id)
        // this.queryParam = {
        //   pid: this.selectedNode.id || 0,
        // }
        this.queryParam.pid = this.selectedNode.id || 0
        var rootTitle = this.selectedNode.title
        this.selectedTips = `${this.selectedTipsDefault}${rootTitle}`
        this.$refs.table.refresh(true)
      } else {
        // console.log(66666)
      }
      //  alert(JSON.stringify(this.selectedNode) )
      this.selectedRows = null
    },
    findByTree(selectedKeys, data) {
      var ss = {}
      var selected = data.filter((item) => item.key == selectedKeys)
      if (isNull(selected)) {
        for (const node of data) {
          var children = node.children
          if (!isNull(children)) {
            selected = this.findByTree(selectedKeys, children)
            if (!isNull(selected)) {
              return selected
            }
          }
        }
      } else {
        return selected
      }
      return selected
    },
  },
  toarray(data) {
    var res = []
    var obj = {}
    for (var item in data) {
      obj = data[item]
      obj.ename = item
      res.push(obj)
    }
    return res
  },
}
</script>

<style lang="less" scoped>
.selectedTips {
  margin-bottom: 5px;
}
</style>
